package com.lyj.linearalgebra.comment.web.servlet;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lyj.linearalgebra.comment.domain.Comment;
import com.lyj.linearalgebra.comment.service.CommentService;
import com.lyj.linearalgebra.post.domain.Post;
import com.lyj.linearalgebra.post.service.PostService;
import com.lyj.linearalgebra.user.dao.UserDao;
import com.lyj.linearalgebra.user.domain.User;

/** 
 * Servlet implementation class CommentServlet
 */
@WebServlet("/CommentServlet")
public class CommentServlet extends BaseServlet {
	
	private CommentService commentService = new CommentService();
	private PostService postService = new PostService();
	
	public String details(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String pid = request.getParameter("pid");
		String username = postService.findUsernameByPid(pid);
		
		request.setAttribute("username", username);
		request.setAttribute("comments", commentService.findAll(pid));
		request.setAttribute("post", postService.findByPid(pid));
		return "f:/details.jsp";
		
	}
	
	public String addComment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		Comment form = CommonUtils.toBean(request.getParameterMap(), Comment.class);
		User user = (User) request.getSession().getAttribute("session_user");
		
		form.setUid(user.getUid());
		form.setCid(CommonUtils.uuid());
		
		String datestyle="yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat format=new SimpleDateFormat(datestyle);
		Date time=new Date();
		String nowtime=format.format(time);
		form.setTime(nowtime);
		
		commentService.addComment(form);
		return details(request, response);
	}
	
}
